<template>
  <div>
    <div class="form">
      <!-- 手机号 -->
      <div>
        <div v-show="props.current === 0" mt-30rpx>
          <div mb-40px>
            <nut-input
              :border="false"
              :input-style="mobileInputStyle"
              placeholder="请输入手机号 (11位)"
              class="mobile"
              focus
              v-model="mobile"
              :disabled="phoneDisable"
              type="number"
              max-length="11" />
          </div>
          <nut-button
            :loading="loading"
            block
            @click="fetchCode"
            :custom-color="!enableFetchCode ? disabledStyle : fetchStyle">
            获取验证码
          </nut-button>
        </div>
        <!-- 输入验证码 -->
        <div v-show="props.current === 1" class="box-code">
          <div mb-40px>
            <nut-code-input
              size="40"
              hairline
              font-size="24"
              space="20"
              :maxlength="6"
              focus
              mode="line"
              @finish="login"
              v-model="code" />
          </div>
          <nut-config-provider
            :theme-vars="{
              cellBoxShadow: 'none',
              cellPadding: '23rpx 0',
              buttonBorderWidth: '0px',
              buttonDefaultBorderColor: 'rgba(255, 255, 255, 1)'
            }">
            <nut-button
              :style="{ '--nut-button-border-width': 0 }"
              class="custom-button"
              :loading="loading"
              @click="reloadFetchCode"
              block
              :custom-color="reloadCode ? disabledStyle : fetchStyle">
              <div flex flex-a-c flex-j-c>
                <span>重新获取</span>
                <div v-show="reloadCode" flex flex-a-c>
                  (
                  <nut-countdown @on-end="reloadTime()" :endTime="endTime" millisecond format="ss" />
                  )
                </div>
              </div>
            </nut-button>
          </nut-config-provider>
        </div>
      </div>
      <!-- <verifyModule
        v-if="enableVerifyModule"
        ref="verificationRef"
        class="verification"
        :business="props.business"
        @send="verification"
      /> -->
    </div>
    <nut-toast ref="toastRef" />
  </div>
</template>
<script setup lang="ts">
import { sendMobile, smsLogin } from '@/api/login'
import { isLogin } from '@/utils/filters'
import {
  disabledStyle,
  fetchStyle,
  mobileInputStyle,
  saveTokenAndRefresh
} from '@/components/useful-template/login/common'
import verifyModule from '@/components/verification/verification.vue' // 验证码模块
import { useStore } from '@/store'
import storage from '@/utils/storage'

const props = defineProps({
  // 是否只验证
  verify: {
    type: Boolean,
    default: false
  },
  current: {
    type: Number,
    default: 0
  },
  business: {
    type: String,
    default: 'LOGIN'
  }
})
const userInfo = storage.getUserInfo()
// const current = ref<number>(0)
const store = useStore()
const enableVerifyModule = ref(false) // 是否展示验证码模块
const mobile = ref<any>(userInfo.mobile) //手机号
const code = ref<string>('') // 验证码
const enableFetchCode = ref(false) // 是否允许获取验证码
const verificationRef = ref<any>(null) // 验证码模块
const clientType = ref<string>('') // 客户端类型
const endTime = ref<any>(Date.now()) // 倒计时
const reloadCode = ref(false) // 是否重新获取code
const loading = ref(false)
const phoneDisable = ref(false)
const emit = defineEmits(['verify', 'update:current', 'fetch'])

watch(
  () => mobile.value,
  (val) => {
    if (val.length === 11) {
      enableFetchCode.value = true
      phoneDisable.value = true
    } else {
      enableFetchCode.value = false
      phoneDisable.value = false
    }
  },{ deep: true, immediate: true }
)
// watch(
//   () => current.value,
//   (val) => {
//     console.log('子组件current改变了, 更新父组件current', val)
//     emit('update:current', val)
//   }
// )
// watch(
//   () => props.current,
//   (val) => {
//     current.value = val
//   },
//   { deep: true, immediate: true }
// )

// 获取验证码
function fetchCode() {
  if (mobile.value.length === 11) {
    fetchVerifyCode()
  }
}
// 重新获取验证码
function reloadFetchCode() {
  code.value = ''
  if (!reloadCode.value) {
    code.value = ''
    fetchVerifyCode()
  }
}

// 重置时间
function reloadTime() {
  reloadCode.value = false
  enableVerifyModule.value = true
}

// 调用验证码进行验证
function getVerify() {
  loading.value = true
  enableVerifyModule.value = true
  setTimeout(() => {
    verificationRef.value.hide()
  }, 500)
}
// 验证
async function verification(val: string) {
  const flag = val === store.access.verificationKey
  loading.value = false
  if (flag) {
    enableVerifyModule.value = false
    // 获取验证码
    fetchVerifyCode()
  }
}

// 获取验证码
async function fetchVerifyCode() {
  const res = await sendMobile(mobile.value, props.business)
  console.log('发送成功', res)
  if (res.data.success) {
    uni.showToast({
      title: res.data.message,
      icon: 'none'
    })
    // current.value = 1
    emit('update:current', 1)
    // 开始倒计时
    reloadCode.value = true
    endTime.value = Date.now() + 60 * 1000
  }
}

// 用户登录
async function login() {
  emit('verify', {
    mobile: mobile.value,
    code: code.value
  })
  if (props.verify) return
  // 判断当前是验证码还是账号密码
  loading.value = true
  // 验证码
  const res = await smsLogin(
    {
      mobile: mobile.value,
      code: code.value
    },
    clientType.value
  )
  loading.value = false
  if (res.data.success) {
    saveTokenAndRefresh(res.data.result.token)
  }
}

onMounted(() => {
  // #ifdef APP-PLUS
  clientType.value = 'APP'
  // #endif
  // #ifdef H5
  clientType.value = 'H5'
  // #endif
  if (isLogin('auth')) {
    // const userInfo = storage.getUserInfo()
    // console.log('userInfo', userInfo)
    // mobile.value = userInfo.mobile
  }
})
</script>
<style>
page {
  background: #fff;
}
</style>
<style lang="scss" scoped>
:root,
page {
  --nut-button-border-width: 0 !important;
}

.custom-button {
  --nut-button-border-width: 0;
}

::v-deep .nut-button--default {
  border: none;
}

.box-code {
  margin-top: 78rpx;
}

.mobile {
  margin-top: 80rpx;
}

.btn {
  border-radius: 100px;
  width: 590rpx;
  margin-top: 97rpx;
  height: 80rpx;
  font-size: 30rpx;
  line-height: 80rpx;
  text-align: center;
  color: #ffffff;
}

.tips {
  font-size: 12px;
  line-height: 20px;
  margin-top: 32rpx;
  width: 546rpx;

  > span {
    color: $main-color;
  }
}
</style>
